import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/models/room.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/page/main.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';

class CreationRoomPage extends StatefulWidget {
  const CreationRoomPage({super.key});

  @override
  State<CreationRoomPage> createState() => _CreationRoomPageState();
}

class _CreationRoomPageState extends State<CreationRoomPage> {
  final TextEditingController _viewPointController = TextEditingController();
  final TextEditingController _roomNameController = TextEditingController();
  String? _selectedImagePath;

  @override
  void dispose() {
    _viewPointController.dispose();
    _roomNameController.dispose();
    super.dispose();
  }

  // 选择图片
  Future<void> _pickImage() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedImagePath = file.path;
        });
      }
    }
  }

  // 创建房间
  void _createRoom() {
    final viewPoint = _viewPointController.text.trim();
    final roomName = _roomNameController.text.trim();

    if (viewPoint.isEmpty) {
      AwakToast.showCustomToast(context, 'Please enter your point of view');
      return;
    }

    if (roomName.isEmpty) {
      AwakToast.showCustomToast(context, 'Please enter room name');
      return;
    }

    // 使用默认图片如果没有选择
    final roomAvatar = _selectedImagePath ?? 'assets/images/learning1.png';

    final room = Room(
      roomName: roomName,
      viewPoint: viewPoint,
      roomAvatar: roomAvatar,
    );

    context.read<AwakBloc>().add(AddRoomEvent(room));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.h),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: GestureDetector(
                        onTap: () => Beamer.of(context).beamBack(),
                        child: Icon(AwakSvg.back),
                      ),
                    ),
                    Center(
                      child: Text('CREATE ROOM', style: AwakText.titleStyle),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 30.h),
              // Point Of View
              Center(
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 12.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      child: TextField(
                        controller: _viewPointController,
                        maxLines: 4,
                        decoration: InputDecoration(
                          hintText: 'Write A Paragraph That You Think Is Good!',
                          hintStyle: AwakText.body14Style.copyWith(
                            color: Colors.black.withValues(alpha: 0.3),
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(
                            bottom: 12.h,
                            left: 12.w,
                            right: 12.w,
                            top: 24.h,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: -25.h,
                      left: 135.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 10.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFF0F44A),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        child: Text(
                          'Point Of View',
                          style: AwakText.body16Style.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 50.h),
              // Room Creation Name
              Center(
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 12.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      child: TextField(
                        controller: _roomNameController,
                        maxLines: 4,
                        decoration: InputDecoration(
                          hintText:
                              'Come Up With A Name That You Are Satisfied With!',
                          hintStyle: AwakText.body14Style.copyWith(
                            color: Colors.black.withValues(alpha: 0.3),
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(
                            bottom: 12.h,
                            left: 12.w,
                            right: 12.w,
                            top: 24.h,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: -25.h,
                      left: 105.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 10.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD3F427),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        child: Text(
                          'Room Creation Name',
                          style: AwakText.body16Style.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 18.h),
              // Room Avatar
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Text(
                  'Room Avatar',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18.sp,
                  ),
                ),
              ),
              SizedBox(height: 8.h),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: _pickImage,
                      child: Container(
                        width: 56.w,
                        height: 56.h,
                        decoration: BoxDecoration(
                          color: Colors.black12,
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 1.w),
                        ),
                        child: _selectedImagePath != null
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(12.r),
                                child: Image.file(
                                  File(_selectedImagePath!),
                                  fit: BoxFit.cover,
                                ),
                              )
                            : Icon(Icons.camera_alt, size: 32.w),
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Text(
                      _selectedImagePath != null
                          ? 'Image Selected'
                          : 'Tap to select image',
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black.withValues(alpha: 0.6),
                      ),
                    ),
                  ],
                ),
              ),
              Spacer(),
              // 确认按钮
              BlocListener<AwakBloc, AwakState>(
                listener: (context, state) {
                  if (state is AwakSuccess) {
                    AwakToast.showCustomToast(context, 'Room created successfully!');
                    // 先切换到社区标签，然后导航到主页面
                    context.read<TabIndexCubit>().setIndex(2); // 社区标签的索引是2
                    Beamer.of(context).beamToNamed(RouterNames.main);
                  } else if (state is RoomFailure) {
                    AwakToast.showCustomToast(context, state.message);
                  }
                },
                child: GestureDetector(
                  onTap: _createRoom,
                  child: Container(
                    width: double.infinity,
                    margin: EdgeInsets.symmetric(horizontal: 18.w, vertical: 12.h),
                    padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      color: const Color(0xFFB6F558),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Text(
                      'Confirm',
                      textAlign: TextAlign.center,
                      style: AwakText.body16Style.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
